package com.hengpeng.itfinoss.controller.borrowinfo;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.annotation.PreDestroy;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.hengpeng.common.persist.entity.AbstractEntity.BoolValue;
import com.hengpeng.common.util.BeanClone;
import com.hengpeng.common.util.MoneyUtil;
import com.hengpeng.common.util.StringHelper;
import com.hengpeng.common.web.tags.ListTag.Pagination;
import com.hengpeng.itfinbase.constants.TransCodeConstants;
import com.hengpeng.itfinbase.message.partner.AddBidInfoRequest;
import com.hengpeng.itfinbase.message.partner.LoansRequest;
import com.hengpeng.itfinbase.message.partner.PartnerTransType;
import com.hengpeng.itfinbase.message.partner.UsrUnFreezeRequest;
import com.hengpeng.itfinbase.persist.BorrowInfo;
import com.hengpeng.itfinbase.persist.BorrowInfo.BorrowStatus;
import com.hengpeng.itfinbase.persist.BorrowInfo.DurationType;
import com.hengpeng.itfinbase.persist.BorrowInfo.InputStatus;
import com.hengpeng.itfinbase.persist.InvestInfo;
import com.hengpeng.itfinbase.persist.UserInfo;
import com.hengpeng.itfinoss.constant.SystemConfigUtil;
import com.hengpeng.itfinoss.controller.BaseController;
import com.hengpeng.itfinoss.controller.util.PageHandlerUtil;
import com.hengpeng.itfinoss.controller.vo.BorrowInfoVo;
import com.hengpeng.itfinoss.service.GuarantorManager;
import com.hengpeng.itfinoss.service.ServiceFactory;
import com.hengpeng.itfinoss.util.DateTimeUtil;
import com.hengpeng.itfinoss.util.InvestUtils;
import com.hengpeng.itfinoss.util.PropertyClone;
import com.hengpeng.itfinoss.util.StringUtils;
/**
 * 标的信息管理
 * @author weiyuan
 */
@Controller
@RequestMapping("/borrowInfo")
public class BorrowInfoController extends BaseController {
	public final static Log logger = LogFactory.getLog(BorrowInfoController.class);

	@Autowired
	private ServiceFactory serviceFactory;

	private final static ExecutorService execute = Executors.newCachedThreadPool();

	@PreDestroy
	public void release()
	{
		if (execute != null)
		{
			execute.shutdown();
		}
	}

	/**
	 * <pre>
	 * 标的列表
	 * </pre>
	 * @param map
	 * @param request
	 * @param borrowName
	 * @param borrowUserName
	 * @param startTime
	 * @param endTime
	 * @return
	 */
	@RequestMapping(value = "/list")
	public String list(ModelMap map, HttpServletRequest request, String borrowName, String borrowUserName,
			String startTime, String endTime)
	{
		map.put("borrowName", borrowName);
		map.put("borrowUserName", borrowUserName);
		map.put("startTime", startTime);
		map.put("endTime", endTime);
		Pagination page = new Pagination(request);
		page.setPageSize(this.getPageSize(request));
		Date start = null;
		Date end = null;
		try
		{
			if (!StringHelper.isEmpty(startTime))
			{
				start = StringHelper.getDateFromString(startTime, "yyyy-MM-dd HH:mm");
			}
			if (!StringHelper.isEmpty(endTime))
			{
				end = StringHelper.getDateFromString(endTime, "yyyy-MM-dd HH:mm");
			}
			List<BorrowInfo> borrowList = serviceFactory
					.getBorrowInfoService()
					.queryList(borrowName, borrowUserName, start, end, new BorrowStatus[] { BorrowStatus.WAITING },
							page.currentPage, page.pageSize).getReturnValue();
			Long count = serviceFactory.getBorrowInfoService()
					.queryCount(borrowName, borrowUserName, start, end, new BorrowStatus[] { BorrowStatus.WAITING })
					.getReturnValue();
			List<BorrowInfoVo> list = new ArrayList<BorrowInfoVo>();
			for (BorrowInfo borrowInfo : borrowList)
			{
				BorrowInfoVo vo = BeanClone.clone(borrowInfo, BorrowInfoVo.class);
				vo.setBorrowDurationDec(borrowInfo.getBorrowDuration()
						+ (borrowInfo.getDurType().equals(DurationType.MONTH) ? "个" : "")
						+ borrowInfo.getDurType().getText());
				vo.setBorrowMoney(MoneyUtil.convertLongFenToYuan(borrowInfo.getBorrowMoney()));
//				vo.setMinInvest(MoneyUtil.convertLongFenToYuan(borrowInfo.getMinInvest()));
//				vo.setMaxInvest(MoneyUtil.convertLongFenToYuan(borrowInfo.getMaxInvest()));
//				vo.setIncMoney(MoneyUtil.convertLongFenToYuan(borrowInfo.getIncMoney()));
				list.add(vo);
			}
			page.setEntityCount(count.intValue());
			map.put("borrowList", list);
			map.put("borrowListPage", page);
			return "borrowInfo/borrowInfoList";
		}
		catch (Exception e)
		{
			logger.error(e);
			return returnError(map, e);
		}
	}

	/**
	 * <pre>
	 * 待排期标的
	 * </pre>
	 * @param map
	 * @param request
	 * @param status
	 * @param borrowName
	 * @param borrowUserName
	 * @param startTime
	 * @param endTime
	 * @return
	 */
	@RequestMapping(value = "/runList/{status}")
	public String runList(ModelMap map, HttpServletRequest request, @PathVariable BorrowStatus status,
			String borrowName, String borrowUserName, String startTime, String endTime)
	{
		map.put("borrowName", borrowName);
		map.put("borrowUserName", borrowUserName);
		map.put("startTime", startTime);
		map.put("endTime", endTime);
		map.put("status", status);
		Pagination page = new Pagination(request);
		page.setPageSize(this.getPageSize(request));
		Date start = null;
		Date end = null;
		try
		{
			if (!StringHelper.isEmpty(startTime))
			{
				start = StringHelper.getDateFromString(startTime, "yyyy-MM-dd HH:mm");
			}
			if (!StringHelper.isEmpty(endTime))
			{
				end = StringHelper.getDateFromString(endTime, "yyyy-MM-dd HH:mm");
			}
			List<BorrowInfo> borrowList = serviceFactory
					.getBorrowInfoService()
					.queryList(borrowName, borrowUserName, start, end, new BorrowStatus[] { status }, page.currentPage,
							page.pageSize).getReturnValue();
			Long count = serviceFactory.getBorrowInfoService()
					.queryCount(borrowName, borrowUserName, start, end, new BorrowStatus[] { status }).getReturnValue();
			List<BorrowInfoVo> list = new ArrayList<BorrowInfoVo>();
			for (BorrowInfo borrowInfo : borrowList)
			{
				BorrowInfoVo vo = BeanClone.clone(borrowInfo, BorrowInfoVo.class);
				vo.setBorrowDurationDec(borrowInfo.getBorrowDuration()
						+ (borrowInfo.getDurType().equals(DurationType.MONTH) ? "个" : "")
						+ borrowInfo.getDurType().getText());
				vo.setBorrowMoney(MoneyUtil.convertLongFenToYuan(borrowInfo.getBorrowMoney()));
				vo.setMinInvest(MoneyUtil.convertLongFenToYuan(borrowInfo.getMinInvest()));
				vo.setMaxInvest(MoneyUtil.convertLongFenToYuan(borrowInfo.getMaxInvest()));
				vo.setIncMoney(MoneyUtil.convertLongFenToYuan(borrowInfo.getIncMoney()));
				vo.setRaiseMoney(MoneyUtil.convertLongFenToYuan(borrowInfo.getRaiseMoney()));
				list.add(vo);
			}
			page.setEntityCount(count.intValue());
			map.put("borrowList", list);
			map.put("borrowListPage", page);
			return "borrowInfo/runList";
		}
		catch (Exception e)
		{
			logger.error(e);
			return returnError(map, e);
		}
	}

	/**
	 * <pre>
	 * 筹款结束标的
	 * </pre>
	 * @param map
	 * @param request
	 * @param borrowName
	 * @param borrowUserName
	 * @param startTime
	 * @param endTime
	 * @return
	 */
	@RequestMapping(value = "/end")
	public String end(ModelMap map, HttpServletRequest request, String borrowName, String borrowUserName,
			String startTime, String endTime)
	{
		map.put("borrowName", borrowName);
		map.put("borrowUserName", borrowUserName);
		map.put("startTime", startTime);
		map.put("endTime", endTime);
		Pagination page = new Pagination(request);
		page.setPageSize(this.getPageSize(request));
		Date start = null;
		Date end = null;
		try
		{
			if (!StringHelper.isEmpty(startTime))
			{
				start = StringHelper.getDateFromString(startTime, "yyyy-MM-dd HH:mm");
			}
			if (!StringHelper.isEmpty(endTime))
			{
				end = StringHelper.getDateFromString(endTime, "yyyy-MM-dd HH:mm");
			}
			BorrowStatus[] status = new BorrowStatus[] { BorrowStatus.END, BorrowStatus.LOANING, BorrowStatus.LOSSING };
			List<BorrowInfo> borrowList = serviceFactory.getBorrowInfoService()
					.queryList(borrowName, borrowUserName, start, end, status, page.currentPage, page.pageSize)
					.getReturnValue();
			Long count = serviceFactory.getBorrowInfoService()
					.queryCount(borrowName, borrowUserName, start, end, status).getReturnValue();
			List<BorrowInfoVo> list = new ArrayList<BorrowInfoVo>();
			for (BorrowInfo borrowInfo : borrowList)
			{
				BorrowInfoVo vo = BeanClone.clone(borrowInfo, BorrowInfoVo.class);
				vo.setBorrowDurationDec(borrowInfo.getBorrowDuration()
						+ (borrowInfo.getDurType().equals(DurationType.MONTH) ? "个" : "")
						+ borrowInfo.getDurType().getText());
				vo.setBorrowMoney(MoneyUtil.convertLongFenToYuan(borrowInfo.getBorrowMoney()));
				vo.setMinInvest(MoneyUtil.convertLongFenToYuan(borrowInfo.getMinInvest()));
				vo.setMaxInvest(MoneyUtil.convertLongFenToYuan(borrowInfo.getMaxInvest()));
				vo.setIncMoney(MoneyUtil.convertLongFenToYuan(borrowInfo.getIncMoney()));
				vo.setRaiseMoney(MoneyUtil.convertLongFenToYuan(borrowInfo.getRaiseMoney()));
				list.add(vo);
			}
			page.setEntityCount(count.intValue());
			map.put("borrowList", list);
			map.put("borrowListPage", page);
			return "borrowInfo/end";
		}
		catch (Exception e)
		{
			logger.error(e);
			return returnError(map, e);
		}
	}

	/**
	 * <pre>
	 * 截止标的
	 * </pre>
	 * @param map
	 * @param request
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/doEnd/{id}")
	public String doEnd(ModelMap map, HttpServletRequest request, @PathVariable Long id)
	{

		List<InvestInfo> l = serviceFactory.getInvestInfoService().getInvestInfos(id,
				new InvestInfo.InvestStatus[] { InvestInfo.InvestStatus.INVESTING });
		if (l != null && l.size() > 0)
		{
			return returnError(map, "该标的有投标中的记录,不能截止");
		}
		BorrowInfo borrow = serviceFactory.getPersistService().get(BorrowInfo.class, id);
		borrow.setStatus(BorrowInfo.BorrowStatus.END);
		serviceFactory.getPersistService().update(borrow);
		return PageHandlerUtil.returnSuccess(map, "截止成功！", "/borrowInfo/runList/RAISE");
	}

	/**
	 * <pre>
	 * 跳转标的排期
	 * </pre>
	 * @param id
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "/preschedule/{id}")
	public String preSchedule(@PathVariable Long id, ModelMap map)
	{
		try
		{
			BorrowInfo borrowInfo = serviceFactory.getPersistService().get(BorrowInfo.class, id);
			BorrowInfoVo vo = BeanClone.clone(borrowInfo, BorrowInfoVo.class);
			vo.setBorrowDurationDec(borrowInfo.getBorrowDuration()
					+ (borrowInfo.getDurType().equals(DurationType.MONTH) ? "个" : "")
					+ borrowInfo.getDurType().getText());
			vo.setBorrowMoney(MoneyUtil.convertLongFenToYuan(borrowInfo.getBorrowMoney()));
			vo.setMinInvest(MoneyUtil.convertLongFenToYuan(borrowInfo.getMinInvest()));
			vo.setMaxInvest(MoneyUtil.convertLongFenToYuan(borrowInfo.getMaxInvest()));
			vo.setIncMoney(MoneyUtil.convertLongFenToYuan(borrowInfo.getIncMoney()));
			vo.setRaiseMoney(MoneyUtil.convertLongFenToYuan(borrowInfo.getRaiseMoney()));
			map.put("borrowInfo", vo);
			return "borrowInfo/schedule";
		}
		catch (Exception ex)
		{
			logger.error(ex);
			return PageHandlerUtil.returnError(map, ex);
		}
	}

	/**
	 * <pre>
	 * 标的排期
	 * </pre>
	 * @param id
	 * @param bidOpenTime
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "/schedule", method = RequestMethod.POST)
	public String schedule(Long id, String bidOpenTime, ModelMap map)
	{
		if (StringHelper.isEmpty(bidOpenTime))
		{
			return PageHandlerUtil.returnError(map, "未选定开标时间!");
		}
		try
		{
			final BorrowInfo borrow = serviceFactory.getPersistService().get(BorrowInfo.class, id);
			borrow.setBidOpenTime(StringHelper.getDateFromString(bidOpenTime, "yyyy-MM-dd HH:mm"));
			borrow.setBidStopTime(DateTimeUtil.addHour(borrow.getBidOpenTime(), borrow.getRaiseDuration()));
			borrow.setStatus(BorrowStatus.SCHEDULED);
			borrow.setInputStatus(InputStatus.WAIT);
			serviceFactory.getPersistService().update(borrow);
			execute.execute(new Runnable()
			{
				@Override
				public void run()
				{
					AddBidInfoRequest addRequest = new AddBidInfoRequest();
					addRequest.setPartnerTransType(PartnerTransType.AddBidInfo);
					addRequest.setProId(borrow.getId().toString());
					addRequest.setBidStartDate(StringHelper.getStringFromDate(borrow.getBidOpenTime(), "yyyyMMddhhmmss"));
					addRequest.setBidEndDate(StringHelper.getStringFromDate(borrow.getBidStopTime(), "yyyyMMddhhmmss"));
					addRequest.setBorrCustId(borrow.getBorrowUserTrustAccountId());
					addRequest.setBorrTotAmt(MoneyUtil.convertFenToYuan(borrow.getBorrowMoney()));
					addRequest.setYearRate(new DecimalFormat("#.00").format((borrow.getBorrowRate() + borrow
							.getRewardRate())));
					addRequest.setGuarCompId(borrow.getGuaranteeUserTrustAccountId());
					Double guarAmt = borrow.getBorrowMoney() * borrow.getGuaranteeFeeRate() / 100;// 担保费用
					addRequest.setGuarAmt(MoneyUtil.convertFenToYuan(guarAmt.longValue()));
					addRequest.setProArea("4402");// 区域深圳
					Date end = null;
					switch (borrow.getRepaymentType())
					{
						case EQUALINTEREST:
							long month = InvestUtils.equalInterest(borrow.getBorrowMoney(),
									(borrow.getBorrowRate() + borrow.getRewardRate()), borrow.getBorrowDuration());
							end = StringUtils.addTime(borrow.getBidStopTime(), borrow.getBorrowDuration(),
									Calendar.MONTH);
							addRequest.setRetAmt(MoneyUtil.convertFenToYuan(month * borrow.getBorrowDuration()));
							addRequest.setRetDate(StringHelper.getStringFromDate(end, "yyyyMMdd"));
							addRequest.setRetType("01");
							break;
						case EQUALPRINCIPAL:
							long total = InvestUtils.equalPrincipal(borrow.getBorrowMoney(),
									(borrow.getBorrowRate() + borrow.getRewardRate()), borrow.getBorrowDuration());// 等额本金还款总额
							end = StringUtils.addTime(borrow.getBidStopTime(), borrow.getBorrowDuration(),
									Calendar.MONTH);
							addRequest.setRetAmt(MoneyUtil.convertFenToYuan(total));
							addRequest.setRetDate(StringHelper.getStringFromDate(end, "yyyyMMdd"));
							addRequest.setRetType("02");
							break;
						case MONTHINTEREST:// 按月付息到期还本
							if (borrow.getDurType().equals(DurationType.MONTH))
							{
								end = StringUtils.addTime(borrow.getBidStopTime(), borrow.getBorrowDuration(),
										Calendar.MONTH);
							}
							else
							{
								end = StringUtils.addTime(borrow.getBidStopTime(), borrow.getBorrowDuration(),
										Calendar.DATE);
							}
							long interest = InvestUtils.rtcapitalInterest(borrow.getBorrowMoney(),
									(borrow.getBorrowRate() + borrow.getRewardRate()), borrow.getBorrowDuration(),
									borrow.getDurType());
							addRequest.setRetDate(StringHelper.getStringFromDate(end, "yyyyMMdd"));
							addRequest.setRetAmt(MoneyUtil.convertFenToYuan(interest + borrow.getBorrowMoney()));
							addRequest.setRetType("03");
							break;
						case RTCAPITALINTEREST:// 一次性还本付息
							if (borrow.getDurType().equals(DurationType.MONTH))
							{
								end = StringUtils.addTime(borrow.getBidStopTime(), borrow.getBorrowDuration(),
										Calendar.MONTH);
							}
							else
							{
								end = StringUtils.addTime(borrow.getBidStopTime(), borrow.getBorrowDuration(),
										Calendar.DATE);
							}
							long rest = InvestUtils.rtcapitalInterest(borrow.getBorrowMoney(),
									(borrow.getBorrowRate() + borrow.getRewardRate()), borrow.getBorrowDuration(),
									borrow.getDurType());
							addRequest.setRetDate(StringHelper.getStringFromDate(end, "yyyyMMdd"));
							addRequest.setRetAmt(MoneyUtil.convertFenToYuan(rest + borrow.getBorrowMoney()));
							addRequest.setRetType("04");
							break;
					}
					addRequest.setTransType(TransCodeConstants.BidTransCode.BID_ADDBIDINFO_REQUEST);
					serviceFactory.getRemoteService().remoteTrans(addRequest);
				}
			});
			return PageHandlerUtil.returnSuccess(map, "标的排期成功", "/borrowInfo/runList/" + BorrowStatus.PASS);
		}
		catch (Exception ex)
		{
			logger.error(ex);
			return PageHandlerUtil.returnError(map, ex);
		}
	}

	/**
	 * <pre>
	 * 放款操作
	 * </pre>
	 * @param id
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "/loan/{id}")
	public String loan(@PathVariable Long id, ModelMap map) {
		try {
			BorrowInfo borrow = serviceFactory.getPersistService().get(BorrowInfo.class, id);
			if (borrow != null) {
				if (borrow.getStatus().equals(BorrowStatus.END) || borrow.getStatus().equals(BorrowStatus.LOANING)) {
					LoansRequest request = new LoansRequest();
					request.setBorrowId(id);
					request.setTransType(TransCodeConstants.BidTransCode.BID_LOANS_REQUEST);
					serviceFactory.getRemoteService().remoteTrans(request);
					return PageHandlerUtil.returnSuccess(map, "放款操作成功！", "/borrowInfo/end");
				} else {
					return PageHandlerUtil.returnError(map, "标的状态为" + borrow.getStatus().getText() + ",不允许放款！");
				}
			} else {
				return PageHandlerUtil.returnError(map, "放款失败，不存在的标的编号:" + id);
			}
		} catch (Exception ex) {
			logger.error(ex);
			return PageHandlerUtil.returnError(map, ex);
		}
	}

	/**
	 * <pre>
	 * 流标操作
	 * </pre>
	 * @param id
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "/loss/{id}")
	public String loss(@PathVariable Long id, ModelMap map) {
		try {
			try {
				BorrowInfo borrow = serviceFactory.getPersistService().get(BorrowInfo.class, id);
				if (borrow != null) {
					if (borrow.getStatus().equals(BorrowStatus.END) || borrow.getStatus().equals(BorrowStatus.LOSSING)) {
						UsrUnFreezeRequest request = new UsrUnFreezeRequest();
						request.setBorrowId(id);
						request.setTransType(TransCodeConstants.BidTransCode.BID_LOSS_REQUEST);
						serviceFactory.getRemoteService().remoteTrans(request);
						return PageHandlerUtil.returnSuccess(map, "流标操作成功！", "/borrowInfo/end");
					} else {
						return PageHandlerUtil.returnError(map, "标的状态为" + borrow.getStatus().getText() + ",不允许流标！");
					}
				} else {
					return PageHandlerUtil.returnError(map, "放款失败，不存在的标的编号:" + id);
				}

			} catch (Exception ex) {
				logger.error(ex);
				return PageHandlerUtil.returnError(map, ex);
			}
		} catch (Exception ex) {
			logger.error(ex);
			return PageHandlerUtil.returnError(map, ex);
		}
	}

	@RequestMapping(value = "/new", method = RequestMethod.GET)
	public String preCreate(ModelMap map)
	{
		List<UserInfo> guartors = serviceFactory.getUserInfoService().getGuartors();
		if (guartors != null && guartors.size() > 0)
		{
			GuarantorManager.addCache(guartors);
			map.put("guartors", guartors);
			return "borrowInfo/addborrowInfo";
		}
		else
		{
			return PageHandlerUtil.returnError(map, "没有担保企业用户不能发布借款申请!");
		}
	}

	@RequestMapping(value = "/get/{id}")
	public String get(@PathVariable Long id, ModelMap map)
	{
		BorrowInfo obj = serviceFactory.getPersistService().get(BorrowInfo.class, id);
		List<UserInfo> guartors = serviceFactory.getUserInfoService().getGuartors();
		if (guartors != null && guartors.size() > 0)
		{
			GuarantorManager.addCache(guartors);
			obj.setBorrowMoney(MoneyUtil.convertLongFenToYuan(obj.getBorrowMoney()));
//			obj.setMinInvest(MoneyUtil.convertLongFenToYuan(obj.getMinInvest()));
//			obj.setMaxInvest(MoneyUtil.convertLongFenToYuan(obj.getMaxInvest()));
//			obj.setIncMoney(MoneyUtil.convertLongFenToYuan(obj.getIncMoney()));
			obj.setRaiseMoney(MoneyUtil.convertLongFenToYuan(obj.getRaiseMoney()));
			map.put("borrowInfo", obj);
			map.put("guartors", guartors);
			return "borrowInfo/updateborrowInfo";
		}
		else
		{
			return PageHandlerUtil.returnError(map, "没有担保企业用户不能修改借款申请!");
		}
	}

	/**
	 * <pre>
	 * 新增标的
	 * </pre>
	 * @param request
	 * @param borrow
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public String add(HttpServletRequest request, BorrowInfo borrow, ModelMap map)
	{
		try
		{
			UserInfo userInfo = serviceFactory.getUserInfoService().getByUserName(borrow.getBorrowUserName());
			if (userInfo == null)
			{
				return PageHandlerUtil.returnError(map, "不存在的借款用户");
			}
			UserInfo guar = GuarantorManager.getGuarantor(borrow.getGuaranteeUserId());
			borrow.setBorrowUserId(userInfo.getId());
			borrow.setIsMakeReceivePlan(BoolValue.NO);
			borrow.setIsMakeRepayPlan(BoolValue.NO);
			borrow.setBorrowUserTrustAccountId(userInfo.getTrustAccountId());
			borrow.setGuaranteeRealName(guar.getRealName());
			borrow.setGuaranteeUserTrustAccountId(guar.getTrustAccountId());
			borrow.setStatus(BorrowStatus.WAITING);
			borrow.setInputStatus(InputStatus.WAIT);
			borrow.setRaiseNum(0);
			borrow.setRaiseMoney(0L);
			borrow.setCreateTime(new Date());
			borrow.setBorrowMoney(borrow.getBorrowMoney() * 100);
			borrow.setMinInvest(borrow.getMinInvest() * 100);
			borrow.setMaxInvest(borrow.getMaxInvest() * 100);
			borrow.setIncMoney(borrow.getIncMoney() * 100);
			serviceFactory.getPersistService().save(borrow);
			return PageHandlerUtil.returnSuccess(map, "新增标的成功", "/borrowInfo/list");
		}
		catch (Exception ex)
		{
			logger.error(ex);
			return PageHandlerUtil.returnError(map, ex);
		}
	}

	/**
	 * <pre>
	 * 修改标的
	 * </pre>
	 * @param request
	 * @param vo
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "/modify", method = RequestMethod.POST)
	public String modify(HttpServletRequest request, BorrowInfo vo, ModelMap map)
	{
		try
		{
			BorrowInfo borrow = serviceFactory.getPersistService().get(BorrowInfo.class, vo.getId());
			borrow.setGuaranteeRealName(GuarantorManager.getGuarantor(vo.getGuaranteeUserId()).getRealName());
			UserInfo userInfo = serviceFactory.getUserInfoService().getByUserName(vo.getBorrowUserName());
			if (userInfo == null)
			{
				return PageHandlerUtil.returnError(map, "不存在的借款用户");
			}
			UserInfo guar = GuarantorManager.getGuarantor(vo.getGuaranteeUserId());
			borrow.setBorrowUserId(userInfo.getId());
			borrow.setIsMakeReceivePlan(BoolValue.NO);
			borrow.setIsMakeRepayPlan(BoolValue.NO);
			borrow.setBorrowUserTrustAccountId(userInfo.getTrustAccountId());
			borrow.setGuaranteeRealName(guar.getRealName());
			borrow.setGuaranteeUserTrustAccountId(guar.getTrustAccountId());
			PropertyClone.copyProperties(borrow, vo, false);
			borrow.setUpdateTime(new Date());
			borrow.setBorrowMoney(borrow.getBorrowMoney() * 100);
			borrow.setMinInvest(borrow.getMinInvest() * 100);
			borrow.setMaxInvest(borrow.getMaxInvest() * 100);
			borrow.setIncMoney(borrow.getIncMoney() * 100);
			serviceFactory.getPersistService().update(borrow);
			return PageHandlerUtil.returnSuccess(map, "修改标的成功", "/borrowInfo/list");
		}
		catch (Exception ex)
		{
			logger.error(ex);
			return PageHandlerUtil.returnError(map, ex);
		}
	}

	@RequestMapping(value = "/preExamine/{id}")
	public String preExamine(@PathVariable Long id, ModelMap map)
	{
		try
		{
			BorrowInfo borrowInfo = serviceFactory.getPersistService().get(BorrowInfo.class, id);
			BorrowInfoVo vo = BeanClone.clone(borrowInfo, BorrowInfoVo.class);
			vo.setBorrowDurationDec(borrowInfo.getBorrowDuration()
					+ (borrowInfo.getDurType().equals(DurationType.MONTH) ? "个" : "")
					+ borrowInfo.getDurType().getText());
			vo.setBorrowMoney(MoneyUtil.convertLongFenToYuan(borrowInfo.getBorrowMoney()));
			vo.setMinInvest(MoneyUtil.convertLongFenToYuan(borrowInfo.getMinInvest()));
			vo.setMaxInvest(MoneyUtil.convertLongFenToYuan(borrowInfo.getMaxInvest()));
			vo.setIncMoney(MoneyUtil.convertLongFenToYuan(borrowInfo.getIncMoney()));
			map.put("borrowInfo", vo);
			return "borrowInfo/examine";
		}
		catch (Exception ex)
		{
			logger.error(ex);
			return PageHandlerUtil.returnError(map, ex);
		}
	}

	@RequestMapping(value = "/examine/{id}/{status}", method = RequestMethod.POST)
	public String examine(@PathVariable Long id, @PathVariable BorrowStatus status, ModelMap map)
	{
		try
		{
			BorrowInfo borrow = serviceFactory.getPersistService().get(BorrowInfo.class, id);
			borrow.setStatus(status);
			borrow.setUpdateTime(new Date());
			serviceFactory.getPersistService().update(borrow);
			return PageHandlerUtil.returnSuccess(map, "审核标的成功", "/borrowInfo/list");
		}
		catch (Exception ex)
		{
			logger.error(ex);
			return PageHandlerUtil.returnError(map, ex);
		}
	}

	@RequestMapping(value = "/detail/{id}")
	public String detail(@PathVariable Long id, HttpServletRequest request, ModelMap map)
	{
		try
		{
			BorrowInfo borrowInfo = serviceFactory.getPersistService().get(BorrowInfo.class, id);
			BorrowInfoVo vo = BeanClone.clone(borrowInfo, BorrowInfoVo.class);
			vo.setBorrowDurationDec(borrowInfo.getBorrowDuration()
					+ (borrowInfo.getDurType().equals(DurationType.MONTH) ? "个" : "")
					+ borrowInfo.getDurType().getText());
			vo.setBorrowMoney(MoneyUtil.convertLongFenToYuan(borrowInfo.getBorrowMoney()));
			vo.setMinInvest(MoneyUtil.convertLongFenToYuan(borrowInfo.getMinInvest()));
			vo.setMaxInvest(MoneyUtil.convertLongFenToYuan(borrowInfo.getMaxInvest()));
			vo.setIncMoney(MoneyUtil.convertLongFenToYuan(borrowInfo.getIncMoney()));
			map.put("borrowInfo", vo);
			Pagination page = new Pagination(request);
			page.setPageSize(this.getPageSize(request));
			List<InvestInfo> investList = serviceFactory.getBorrowInfoService()
					.queryInvestList(id, page.currentPage, page.pageSize).getReturnValue();
			for (InvestInfo investInfo : investList)
			{
				investInfo.setInvestMoney(MoneyUtil.convertLongFenToYuan(investInfo.getInvestMoney()));
			}
			Long count = serviceFactory.getBorrowInfoService().queryInvestCount(id).getReturnValue();
			page.setEntityCount(count.intValue());
			map.put("investList", investList);
			map.put("investListPage", page);
			return "borrowInfo/detail";
		}
		catch (Exception ex)
		{
			logger.error(ex);
			return PageHandlerUtil.returnError(map, ex);
		}
	}
	/**
	 * 导入身份证正面
	 * @param request
	 * @param map
	 * @param filepath
	 * @param printWriter
	 */
	@RequestMapping(value = "/importidfront", method = RequestMethod.POST)
	public String importidfront (HttpServletRequest request,HttpServletResponse response, ModelMap map,
			@RequestParam MultipartFile idfront, String type) throws Exception {
		
		response.setContentType("text/html;charset=GBK");
	    request.setCharacterEncoding("GBK");
	    if (idfront.getSize() > 2 * 1024 * 1024) {
			map.put("info", "导入文件最大不能超过2M");
		} else {
			String filePath = request.getRealPath("/upload");// 取系统当前路径
			String newfileName = System.currentTimeMillis()+ idfront.getOriginalFilename().substring(idfront.getOriginalFilename().lastIndexOf('.'));
			OutputStream bos = new FileOutputStream(filePath + "/"+ newfileName);
			InputStream in = idfront.getInputStream();
			int bytesRead = 0;
			byte[] buffer = new byte[8192];
			while ((bytesRead = in.read(buffer, 0, 8192)) != -1) {
				bos.write(buffer, 0, bytesRead);// 将文件写入服务器
			}
			bos.close();
			in.close();
			map.put("type", type);
	        map.put("info", "success");
	        map.put("filename", newfileName);
	        map.put("filepath", SystemConfigUtil.getConfigValue("oss_domainName") + "upload/" + newfileName);
		}
        return "borrowInfo/importfile";
	}
	/**
	 * 导入身份证反面
	 * @param request
	 * @param map
	 * @param filepath
	 * @param printWriter
	 */
	@RequestMapping(value = "/importidback", method = RequestMethod.POST)
	public String importidback (HttpServletRequest request,HttpServletResponse response, ModelMap map,
			@RequestParam MultipartFile idback, String type) throws Exception {
		
		response.setContentType("text/html;charset=GBK");
	    request.setCharacterEncoding("GBK");
	    if (idback.getSize() > 2 * 1024 * 1024) {
			map.put("info", "导入文件最大不能超过2M");
		} else {
			String filePath = request.getRealPath("/upload");// 取系统当前路径
			String newfileName = System.currentTimeMillis()+ idback.getOriginalFilename().substring(idback.getOriginalFilename().lastIndexOf('.'));
			OutputStream bos = new FileOutputStream(filePath + "/"+ newfileName);
			InputStream in = idback.getInputStream();
			int bytesRead = 0;
			byte[] buffer = new byte[8192];
			while ((bytesRead = in.read(buffer, 0, 8192)) != -1) {
				bos.write(buffer, 0, bytesRead);// 将文件写入服务器
			}
			bos.close();
			in.close();
			map.put("type", type);
	        map.put("info", "success");
	        map.put("filename", newfileName);
	        map.put("filepath", SystemConfigUtil.getConfigValue("oss_domainName") + "upload/" + newfileName);
		}
        return "borrowInfo/importfile";
	}
	/**
	 * 上传企业银行开户许可证
	 * @param request
	 * @param response
	 * @param map
	 * @param bankpermit
	 * @param type
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/importbankpermit", method = RequestMethod.POST)
	public String importbankpermit (HttpServletRequest request,HttpServletResponse response, ModelMap map,
			@RequestParam MultipartFile bankpermit, String type) throws Exception {
		
		response.setContentType("text/html;charset=GBK");
	    request.setCharacterEncoding("GBK");
	    if (bankpermit.getSize() > 2 * 1024 * 1024) {
			map.put("info", "导入文件最大不能超过2M");
		} else {
			String filePath = request.getRealPath("/upload");// 取系统当前路径
			String newfileName = System.currentTimeMillis()+ bankpermit.getOriginalFilename().substring(bankpermit.getOriginalFilename().lastIndexOf('.'));
			OutputStream bos = new FileOutputStream(filePath + "/"+ newfileName);
			InputStream in = bankpermit.getInputStream();
			int bytesRead = 0;
			byte[] buffer = new byte[8192];
			while ((bytesRead = in.read(buffer, 0, 8192)) != -1) {
				bos.write(buffer, 0, bytesRead);// 将文件写入服务器
			}
			bos.close();
			in.close();
			map.put("type", type);
	        map.put("info", "success");
	        map.put("filename", newfileName);
	        map.put("filepath", SystemConfigUtil.getConfigValue("oss_domainName") + "upload/" + newfileName);
		}
        return "borrowInfo/importfile";
	}
	/**
	 * 上传上年度利润报表
	 * @param request
	 * @param response
	 * @param map
	 * @param profit
	 * @param type
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/importprofit", method = RequestMethod.POST)
	public String importprofit (HttpServletRequest request,HttpServletResponse response, ModelMap map,
			@RequestParam MultipartFile profit, String type) throws Exception {
		response.setContentType("text/html;charset=GBK");
	    request.setCharacterEncoding("GBK");
	    if (profit.getSize() > 2 * 1024 * 1024) {
			map.put("info", "导入文件最大不能超过2M");
		} else {
			String filePath = request.getRealPath("/upload");// 取系统当前路径
			String newfileName = System.currentTimeMillis()+ profit.getOriginalFilename().substring(profit.getOriginalFilename().lastIndexOf('.'));
			OutputStream bos = new FileOutputStream(filePath + "/"+ newfileName);
			InputStream in = profit.getInputStream();
			int bytesRead = 0;
			byte[] buffer = new byte[8192];
			while ((bytesRead = in.read(buffer, 0, 8192)) != -1) {
				bos.write(buffer, 0, bytesRead);// 将文件写入服务器
			}
			bos.close();
			in.close();
			map.put("type", type);
	        map.put("info", "success");
	        map.put("filename", newfileName);
	        map.put("filepath", SystemConfigUtil.getConfigValue("oss_domainName") + "upload/" + newfileName);
		}
        return "borrowInfo/importfile";
	}
}
